"""
Case Type   : 系统内部使用工具
Case Name   : gs_ctl init：指定参数--xlogdir，所设置的目录不为空
Create At   : 2022-07-28
Owner       : liu-tong-8848
Description :
    1.创建文件
    2.执行gs_ctl init的命令
    3.查看生成初始化的datdir目录
    4.清理环境
Expect      :
    1.成功
    2.失败
    3.失败
    4.成功
History     :
"""

import unittest
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
import os


class Tools(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.userNode = Node('PrimaryDbUser')
        self.DB_ENV_PATH = macro.DB_ENV_PATH
        self.dir_path = os.path.join(macro.DB_INSTANCE_PATH, 'datadir')
        self.log_path = os.path.join(macro.DB_INSTANCE_PATH, 'logdir')
        self.filename = os.path.join(self.log_path, 'ljptest.txt')
        self.nodename = 'nodename_142'

    def test_systools(self):
        self.logger.info(f'-----{os.path.basename(__file__)}' + ' start-----')

        text = '--step1:创建文件；expect：成功--'
        self.logger.info(text)
        excute_cmd0 = f'mkdir {self.log_path};touch {self.filename};'
        self.logger.info(excute_cmd0)
        msg0 = self.userNode.sh(excute_cmd0).result()
        self.logger.info(msg0)

        text = '--step2:执行gs_ctl init的命令；expect：失败--'
        self.logger.info(text)
        excute_cmd1 = f'source {self.DB_ENV_PATH};' \
                      f'gs_ctl init -D {self.dir_path} -o ' \
                      f'"--nodename="{self.nodename}" -w ' \
                      f'"{self.userNode.ssh_password}" ' \
                      f'--xlogdir="{self.log_path}""'
        self.logger.info(excute_cmd1)
        msg1 = self.userNode.sh(excute_cmd1).result()
        self.logger.info(msg1)
        self.assertIn('exists but is not empty', msg1, text + '执行失败')

        text = '--step3:查看生成初始化的datdir目录；expect：失败--'
        self.logger.info(text)
        excute_cmd2 = f'ls {self.dir_path}'
        self.logger.info(excute_cmd2)
        msg2 = self.userNode.sh(excute_cmd2).result()
        self.logger.info(msg2)
        self.assertIn('No such file or directory', msg2, text + '执行失败')

    def tearDown(self):
        text = '--step4:清理环境；expect：成功--'
        self.logger.info(text)
        excute_cmd1 = f'rm -rf {self.log_path};ls {self.log_path}'
        self.logger.info(excute_cmd1)
        msg1 = self.userNode.sh(excute_cmd1).result()
        self.logger.info(msg1)
        self.assertIn('No such file or directory', msg1, text + '执行失败')
        self.logger.info(
            f'-----{os.path.basename(__file__)}' + ' end-----')


